package com.cfpamf.ms.insur.pay.config;

import com.cfpamf.ms.insur.pay.constant.BaseConstants;
import com.cfpamf.ms.insur.pay.integration.wxpay.WxClientManager;
import com.cfpamf.ms.insur.wx.client.WechatPayClient;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.RegExUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Create By zhengjing on 2019-09-25 11:08
 */
@Configuration
@ConfigurationProperties("wxpay")
@Getter
@Setter
public class WxPayConfig {

    private static final String PRIMARY_SYSTEM_CODE = BaseConstants.PRIMARY_SYSTEM_CODE;

    /**
     * 系统详情
     */
    private Map<String, WxPayProperties> bizSystemProperties;


    @Bean
    @Primary
    public WxClientManager clientManager() {
        ObjectMapper objectMapper = new XmlMapper();
        objectMapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.enable(JsonGenerator.Feature.IGNORE_UNKNOWN);
        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        if (MapUtils.isEmpty(bizSystemProperties)) {
            throw new IllegalArgumentException("未配置任何微信信息");
        }

        //
        Map<String, WechatPayClient> clientMap = new ConcurrentHashMap<>();
        bizSystemProperties.forEach((key, value) -> {
            if (StringUtils.isBlank(value.getSystemCode())) {
                value.setSystemCode(key);
            }
            clientMap.put(value.getSystemCode(), WechatPayClient.builder()
                    .apiKey(value.getMchKey())
                    .appId(value.getTencentTasId())
                    .mapper(objectMapper)
                    .mchId(value.getMchId())
                    .certFile(getCertData(value.getKeyPath()))
                    .build());
        });
        return new WxClientManager(clientMap,
                clientMap.get(PRIMARY_SYSTEM_CODE),
                bizSystemProperties,
                bizSystemProperties.get(PRIMARY_SYSTEM_CODE));
    }

//    @Bean
//    @Primary
//    public WxClientManager wxClientManager(ApplicationContext applicationContext) {
//
//        if (MapUtils.isEmpty(bizSystemProperties)) {
//            throw new IllegalArgumentException("未配置任何微信信息");
//        }
//
//        BeanFactory beanFactory;
//
//        //构建xmlMapper
//
//        ObjectMapper objectMapper = new XmlMapper();
//        objectMapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS);
//        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
//        objectMapper.enable(JsonGenerator.Feature.IGNORE_UNKNOWN);
//        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
//
//        return WechatPayClient.builder()
////                .apiKey(wxPayProperties.getMchKey())
//                .appId(wxPayProperties.getTencentTasId())
//                .mapper(objectMapper)
//                .mchId(wxPayProperties.getMchId())
//                .certFile(getCertData(wxPayProperties.getKeyPath()))
//                .build();
//    }

    private byte[] getCertData(String path) {

        InputStream inputStream;
        if (StringUtils.isBlank(path)) {
            throw new IllegalArgumentException("请确保证书文件地址keyPath已配置");
        }

        final String prefix = "classpath:";
        String fileHasProblemMsg = "证书文件【" + path + "】有问题，请核实！";
        String fileNotFoundMsg = "证书文件【" + path + "】不存在，请核实！";
        if (path.startsWith(prefix)) {
            String classPath = RegExUtils.removeFirst(path, prefix);
            if (!classPath.startsWith("/")) {
                classPath = "/" + classPath;
            }
            inputStream = WxPayConfig.class.getResourceAsStream(classPath);
            if (inputStream == null) {
                throw new IllegalArgumentException(fileNotFoundMsg);
            }
        } else if (path.startsWith("http://") || path.startsWith("https://")) {
            try {
                inputStream = new URL(path).openStream();
                if (inputStream == null) {
                    throw new IllegalArgumentException(fileNotFoundMsg);
                }
            } catch (IOException e) {
                throw new IllegalArgumentException(fileNotFoundMsg, e);
            }
        } else {
            try {
                File file = new File(path);
                if (!file.exists()) {
                    throw new IllegalArgumentException(fileNotFoundMsg);
                }
                inputStream = new FileInputStream(file);
            } catch (IOException e) {
                throw new IllegalArgumentException(fileHasProblemMsg, e);
            }
        }
        try {
            return IOUtils.toByteArray(inputStream);
        } catch (IOException e) {
            throw new IllegalArgumentException(fileHasProblemMsg, e);
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                //skip
            }
        }
    }


//        try {
//            KeyStore keystore = KeyStore.getInstance("PKCS12");
//            char[] partnerId2charArray = this.getMchId().toCharArray();
//            keystore.load(inputStream, partnerId2charArray);
//            this.sslContext = SSLContexts.custom().loadKeyMaterial(keystore, partnerId2charArray).build();
//            return this.sslContext;
//        } catch (Exception e) {
//            throw new WxPayException("证书文件有问题，请核实！", e);
//        } finally {
//            IOUtils.closeQuietly(inputStream);
//        }}
}
